<?php

/************************************************************
/* Custom fields for portfolio
/************************************************************/

/// CREATE METABOXES

	
	add_action( 'admin_init', 'add_work_fields' );
	add_action( 'save_post', 'save_work_custom_values');
	
	
if ( ! function_exists( 'add_work_fields' ) ) {
	function add_work_fields() {
		add_meta_box( 'works-images-fields', __( "Images/Videos of project", 'dronetv' ), 'works_images_fields', 'works', 'normal', 'high' );
		add_meta_box( 'works-additional-fields', __( "Additional Info &amp; Preferences", 'dronetv' ), 'works_additional_fields', 'works', 'normal', 'high' );
	}
}


if ( ! function_exists( 'md_create_fields' ) ) {		
	function md_create_fields($args) {
		global $post;
		
		$valtype='';
		$valtitle='';
		$valdesc='';
		$valname='';
		$valopt='';
		
		foreach($args as $foo) {
			
			if(isset($foo['type'])) $valtype=$foo['type'];
			if(isset($foo['title'])) $valtitle=$foo['title'];
			if(isset($foo['desc'])) $valdesc=$foo['desc'];
			if(isset($foo['name'])) $valname=$foo['name'];
			if(isset($foo['options'])) $valopt=$foo['options'];
			
			$inp = get_post_meta( $post->ID, $valname, true );
			
			$argsm = array($valtype,$valtitle,$valdesc,$valname,$inp,$valopt);
			echo md_cc_field($argsm);
		}
	}
}



if ( ! function_exists( 'works_additional_fields' ) ) {
	function works_additional_fields() { 
		$args = array(
						array(
							'type'=>'info',
							'desc'=>''
						),
						array(
							'type'=>'tfield',
							'title'=>'Client Name',
							'name'=>'work-client',
							'desc'=>''
						),
						array(
							'type'=>'tfield',
							'title'=>'Project URL',
							'name'=>'work-url',
							'desc'=>''
						),
						array(
							'type'=>'tfielddate',
							'title'=>'Project Completion Date',
							'name'=>'work-date',
							'desc'=>''
						),
						array(
							'type'=>'select',
							'title'=>'Project Description Positioning',
							'name'=>'work-desc-position',
							'desc'=>'',
							'options'=>array('top'=>'Top of the Project', 'bottom'=>'Bottom of the project')
						)
				);
		return md_create_fields($args);
	}
}



if ( ! function_exists( 'works_images_fields' ) ) {
	function works_images_fields() { 
		$args = array(	
						array(
							'type'=>'info-array',
							'desc'=>__('<span style="font-size:11px;line-height:14px;"><strong>Images :</strong> Click to "Add New Image" button in order to select from library or upload. You can add more than one Image/Video and re-order items. <br>Images are shown as <strong>880px</strong> maximum width in your project canvas. <br>If you\'ll upload images smaller than <strong>880px</strong>, those will be shown as in their original size as centered.						
							<br><br><strong>Videos :</strong> Click to "Add New Video" button in order to add video embed code which is generated by video service website such as youtube, vimeo, dailymotion. <br>Given embed video sizes will be ignored and those will be automatically stretched to fit. <br><strong>NOTE :</strong> You MUST click update button in order to save all changes</span>','dronetv')
						),array(
							'type'=>'imagearr',
							'title'=>'',
							'name'=> 'work-media',
							'desc'=>''
						)
				);
		return md_create_fields($args);
	}

}
	


if ( ! function_exists( 'works_video_fields' ) ) {	
	function works_video_fields() { 
		$args = array(	
						array(
							'type'=>'info',
							'desc'=> __('Put video embed code which is generated by video service website such as youtube, vimeo etc. Any video service website will be accepted. <br>Also you don\'t need to worry about width and height of your embeded code. It will be stretched horizontally on your page with preserved constraint proportions.','dronetv')
						),array(
							'type'=>'tarea',
							'title'=>'Video Embed',
							'name'=>'work-video',
							'desc'=>''
						)
				);
		return md_create_fields($args);
	}
}


	
	/////// BOX CREATOR

if ( ! function_exists( 'wrap' ) ) {	
	function wrap($pick, $args=array()) {
		$spid = '';
		if($pick==2) {
			return $sh = '</td></table>';
		}else{
			if($args[0]=='imagearr') { 
				$spid = 'id="md-sortable-media"';
			}
			return $sh = '<table class="custom-fields form-table"><tr><th><input type="hidden" name="work_token" value="'.wp_create_nonce( basename(__FILE__) ).'" />
			<label for="">'.$args[1].'</label><br /><p>'.__( $args[2], 'dronetv' ).'</p></th><td '.$spid.'>';
		}
	}
}


if ( ! function_exists( 'createToken' ) ) {
	function createToken() { 
		//echo '<input type="hidden" name="work_token" value="'.wp_create_nonce( basename(__FILE__) ).'" />';
	}
}



if ( ! function_exists( 'md_cc_field' ) ) {	
	function md_cc_field ($args=array()) {
		
		$fieldid = 1;
		$idkey = "dpost-";
	
		$idkey = $idkey.$fieldid; 
		if($args[0]=='info' || $args[0]=='info-array') {
			if($args[0]=='info-array') {
			$res = '<table class="custom-fields form-table"><tr><td colspan="2">
					<a href="javascript:void(0);" class="nhp-opts-upload button-secondary" rel-id="new">Add New Image</a>
					<a href="javascript:void(0);" class="add-more-videos button-secondary" rel-id="new">Add Video</a>
					<br class="clear"><br class="clear">
					<h4>'.$args[2].'</h4>
					</td></tr></table>';	
			}else{
			$res = '<table class="custom-fields form-table"><tr><td colspan="2"><h4>'.$args[2].'</h4></td></tr></table>';
			}
		}else{
		$res = wrap(1,$args);
		$res .= fieldType($args);
		$res .= wrap(2);
		}
		$fieldid ++;
		
		return $res;
	}
}



if ( ! function_exists( 'fieldType' ) ) {
	function fieldType($args) {
		
		global $post;
		
		$type = $args[0];
		$key = $args[3];
		$val = $args[4];
		$output = '';
		
		if($type=='tarea') {
			return $output= '<textarea id="'.$key.'" cols="60" rows="3" name="'.$key.'">'.$val.'</textarea>';
		}
		if($type=='color') {
			$output .= '<div id="' . $key . '_picker" class="colorSelector"><div style="background-color: '.$val.'"></div></div>';
		    $output .= '<input class="of-color" name="'.$key.'" id="'. $key .'" type="text" style="width: 80px;padding: 5px;margin-top: 0px;margin-left: 5px;" value="'. $val .'" />';
			return  $output;
		}
		if($type=='select') {
			
			$output .= '<select id="'.$key.'" name="'.$key.'">';
				foreach($args[5] as $k=>$v) {
					if($val==$k) { $sel1 = 'selected'; }else{ $sel1= '';}
					$output .= '<option value="'.$k.'" '.$sel1.'>'.$v.'</option>';
				}
			$output .= '</select>';
			return $output;
			
		}
		if($type=='tfield') {
			return $output= '<input id="'.$key.'" class="upload" type="text" name="'.$key.'" value="'.$val.'" />';
		}
		if($type=='tfielddate') {
			return $output= '<input id="'.$key.'" class="upload get-datepicker" type="text" name="'.$key.'" value="'.$val.'" />';
		}
		
		if($type=='imagearr') {
			$s1=0;
			$s2=0;
			$output = "";
			$media = unserialize($val);
			$mediacaption = unserialize(get_post_meta( $post->ID, 'work-media-caption', true ));
			$mediavideo = unserialize(get_post_meta( $post->ID, 'work-media-video', true ));
			
			if(is_array($media)) {
				foreach($media as $v) {
					if($v=='videoembed') {
					$output .= '<div class="imgarr"><span class="imgside">';
					$output .= '<input type="hidden" name="work-media[]" value="videoembed" />';
					$output .= '<img width="120" class="screenshot" src="'.ADMIN_IMG_DIRECTORY.'youtube.png" /></span><span>';
					$output .= '<strong>Video Embed</strong><br class="clear" >';
					$output .= '<textarea id="work-media-video-'.$s1.'" cols="60" rows="3" class="video-caption" name="work-media-video[]">'.stripslashes($mediavideo[$s1]).'</textarea><br class="clear">';
					$output .= '<a href="javascript:void(0);" class="admin-upload-remove button-secondary" rel-id="work-media-'.$s1.'">'.__('Remove', 'dronetv').'</a>';
					$output .= '</span><br class="clear"></div>';
					$s1++;
					}else{
					$output .= '<div class="imgarr"><span class="imgside">';
					$output .= '<input type="hidden" id="work-media-'.$s2.'" name="work-media[]" value="'.$v.'" />';
					$output .= '<div class="imgwindow"><img width="120" class="screenshot" id="sc-'.$s2.'" src="'.$v.'" /></div>';
					$output .= '</span><span>';
					$output .= '<strong>Image Caption</strong><br class="clear" >';
					$output .= '<textarea id="work-media-caption-'.$s2.'" cols="60" rows="3" class="work-caption" name="work-media-caption[]">'.stripslashes($mediacaption[$s2]).'</textarea>';
					$output .= '<a href="javascript:void(0);" class="admin-upload-remove button-secondary" rel-id="work-media-'.$s2.'">'.__('Remove', 'dronetv').'</a><br class="clear">';
					$output .= '</span><br class="clear"></div>';
					$s2++;
					}
				}
			}
			return $output;
		}
		
	}
}





if ( ! function_exists( 'save_work_custom_values' ) ) {
	function save_work_custom_values( $post_id ) {
		  
		  global $post;
		  // verify if this is an auto save routine. 
		  // If it is our form has not been submitted, so we dont want to do anything
		  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
			  return;
	
		  // verify this came from the our screen and with proper authorization,
		  // because save_post can be triggered at other times
		  if(isset($_POST['work_token'])) {
			  if ( !wp_verify_nonce( $_POST['work_token'], basename( __FILE__ ) ) )
				return;
		  }else{
				return;  
		  }
		  
		  // Check permissions
		  if ( 'page' == $_POST['post_type'] ) 
		  {
			if ( !current_user_can( 'edit_page', $post_id ) )
				return;
		  }
		  else
		  {
			if ( !current_user_can( 'edit_post', $post_id ) )
				return;
		  }
	
	
		//// Handle custom values
		if( $post->post_type == "works") {
				foreach($_POST as $inp => $val) {
					if(strpos($inp,'work-')!==false) {
						
					if($inp=='work-media' || $inp=='work-media-caption' || $inp=='work-media-video') {
						$varm = addslashes( serialize( $val));
					}else{
						$varm = stripslashes( htmlspecialchars( $val));	
					}
				
					update_post_meta($post->ID, $inp, $varm);
					}
				}	
				if(isset($_POST['work-media'])) {
					if(count($_POST['work-media'])==0) {
						update_post_meta($post->ID, 'work-media', '');	
						update_post_meta($post->ID, 'work-media-caption', '');	
						update_post_meta($post->ID, 'work-media-video', '');	
					}
				}
		}	
		
	}
}
?>